using Godot;
using System;

public partial class PauseMenu : CanvasLayer
{
	PanelContainer panelContainer;
	PackedScene optionsMenuScene = GD.Load<PackedScene>("res://scenes/ui/options_menu.tscn");
	ScreenTransition screenTransition;
	bool isClosing = false;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		
		GetTree().Paused = true;
		screenTransition = GetNode<ScreenTransition>("/root/ScreenTransition");

		panelContainer = GetNode<PanelContainer>("%PanelContainer");
		panelContainer.PivotOffset = panelContainer.Size/2;

		GetNode<SoundButton>("%ResumeButton").Pressed += OnResumePressed;
		GetNode<SoundButton>("%OptionsButton").Pressed += OnOptionsPressed;
		GetNode<SoundButton>("%QuitButton").Pressed += OnQuitPressed;
		
		GetNode<AnimationPlayer>("AnimationPlayer").Play("default");
		Tween tween = CreateTween();
		tween.TweenProperty(panelContainer,"scale",Vector2.Zero,0);
		tween.TweenProperty(panelContainer,"scale",Vector2.One,.3)
		.SetEase(Tween.EaseType.Out).SetTrans(Tween.TransitionType.Back);
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

	public void close(){
		if(isClosing){
			return;
		}
		isClosing = true;
		GetNode<AnimationPlayer>("AnimationPlayer").PlayBackwards("default");
		Tween tween = CreateTween();
		tween.TweenProperty(panelContainer,"scale",Vector2.One,0);
		tween.TweenProperty(panelContainer,"scale",Vector2.Zero,.3)
		.SetEase(Tween.EaseType.In).SetTrans(Tween.TransitionType.Back);

		GetTree().Paused = false;
		tween.Finished+=QueueFree;
	}

	public override void _UnhandledInput(InputEvent @event)
    {
		if(@event.IsActionPressed("pause")){
			GetTree().Root.SetInputAsHandled();
			this.close();
		}
        base._UnhandledInput(@event);
    }

	public void OnResumePressed(){
		this.close();
	}

	public async void OnOptionsPressed(){
		screenTransition.Transition();
		await ToSignal(screenTransition,nameof(screenTransition.TransitionedHalfway)); //等待信号结束
		OptionsMenu optionsMenuInstance = optionsMenuScene.Instantiate() as OptionsMenu;
		AddChild(optionsMenuInstance);
		optionsMenuInstance.BackPressed += ()=>{this.OnOptionsBackPressed(optionsMenuInstance);};
	}

	public void OnQuitPressed(){
		GetTree().Paused = false;
		GetTree().ChangeSceneToFile("res://scenes/ui/main_menu.tscn");
	}

	public void OnOptionsBackPressed(OptionsMenu optionsMenu){
		optionsMenu.QueueFree();
	}
}
